package io.renren.modules.file;

import io.renren.common.utils.Result;
import io.renren.modules.eightapp.service.EiHouseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Admin
 * @version v1.0.0
 * @className ImageController.java
 * @description
 * @date 2022-11-16 13:51:14
 */
@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    EiHouseInfoService eiHouseInfoService;

    /**
     * 获取图片
     */
    @GetMapping("img")
    public void loadPhoto(HttpServletResponse response, String name) {
        String photoPath;

        try {
            //得到项目中图片保存的路径
            photoPath = new File("").getCanonicalPath() + File.separator + "files";
        } catch (IOException e) {
            throw new RuntimeException("获取项目路径失败", e);
        }
        photoPath += File.separator + name;


        //将一个图片加载到内存
        BufferedImage image;
        try {
            image = ImageIO.read(new FileInputStream(photoPath));
        } catch (IOException e) {
            throw new RuntimeException("把图片加载到内存失败", e);
        }

        // 将图片输出给浏览器
        // 声明返回的是png格式的图片
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            //不用关闭这个流，spring会自动帮我们关闭这个流。
        } catch (IOException e) {
            throw new RuntimeException("响应图片失败，服务器发生异常!", e);
        }
    }

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        try {
            // 保证文件名的唯一，截取文件名后缀 例如：aaa.jpg
            String originalFilename = multipartFile.getOriginalFilename();
            // 截取文件名后缀 .jpg
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成唯一文件名 拼接成为 dadesbawe-d5aa64.jpg
            String newFile = UUID.randomUUID() + substring;
            // 指定上传目录--->时间目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            // 2022-02-16 日期目录
//            String serverPath = new File("").getCanonicalPath() + File.separator + "files";
            String serverPath = System.getProperty("user.dir") + File.separator + "files" + File.separator + "park";
            // E://temp/${dir}/2022/02/16
            File targetFile = new File(serverPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 将文件上传到指定目录
            File targetFileName = new File(targetFile, newFile);
            //最终目录: E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg

            multipartFile.transferTo(targetFileName);
            // 将用户选择的aaa.jpg 上传到E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg
            if (substring.equals(".xlsx")){
                return new Result().ok(newFile);
            }else {
                String picfile = targetFileName.toString().substring(44);
                String newpic = picfile.replaceAll("\\\\", "/");
                return new Result().ok("/file/img?name=" + newpic);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error("上传失败");
        }
    }

    @DeleteMapping("{fileInfo}")
    public Result deleteFile(@PathVariable("fileInfo") String fileInfo) throws IOException {
        String Path = System.getProperty("user.dir");
        String suffix = System.getProperty("user.dir") + File.separator + "files" + File.separator + "park" + File.separator;
        System.out.println(fileInfo);
        String filename="";
        if (fileInfo.substring(fileInfo.lastIndexOf(".")).equals(".xlsx")){
            filename = suffix + fileInfo;
        }else {
            filename=suffix + fileInfo.replaceAll("\\\\", "\\\\\\\\");
        }

        File file = new File(filename);

        System.out.println(file);
        if (file.exists()) {
            boolean deleteRight=file.delete();
            return new Result().ok("删除成功");
        }
        return new Result().error("文件不存在");
    }



}
